﻿var net = require('net');
exports.TCPClient = function (ip, port, onConected, onReceived) {

    this.socket = net.createConnection(port, ip, onConected);

//    this.socket.setKeepAlive(true, 1000);

    this.send = function (tid, content) {
        var data = bufDA.getBuf(tid, content);
        this.socket.write(data);
    };

    this.socket.on('data', function (data) {
        console.log(data);
        var data = bufDA.getData(data);
        onReceived(data);
    });

    return this;
};

var bufDA = {
    getBuf: function (tid, content) {
        var l = Buffer.byteLength(content);
        var buf = new Buffer(l + 8)
        buf.writeInt32LE(tid, 0);
        buf.writeInt32LE(l, 4);
        buf.write(content, 8);
        return buf;
    },
    getData: function (buf) {
        var data = {};
        data.tid = buf.readInt32LE(0);
        var len = buf.readInt32LE(4);
        data.content = buf.slice(8).toString();
        return data;
    }
}
